package application;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class NetServer {
	
	private static NetServer netServer = null;
	
	private SocketAcceptor acceptor = new NioSocketAcceptor(8);
	
	private DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
	
	public static NetServer getInstances() {
		if (null == netServer) {
			netServer = new NetServer();
		}
		return netServer;
	}
	
	private NetServer(){
		PrefixedStringCodecFactory factory  = new PrefixedStringCodecFactory(Charset.forName("UTF-8"));
		factory.setDecoderPrefixLength(4);
		factory.setEncoderPrefixLength(4);
		factory.setDecoderMaxDataLength(100000240);
		factory.setEncoderMaxDataLength(100000240);
//		acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
		chain.addLast("codec", new ProtocolCodecFilter(factory));
		acceptor.setHandler(ServerHandler.getInstances());
		SocketSessionConfig config = acceptor.getSessionConfig();
		config.setIdleTime(IdleStatus.BOTH_IDLE, 60);
		config.setIdleTime(IdleStatus.READER_IDLE, 60);
		config.setIdleTime(IdleStatus.WRITER_IDLE, 60);
		try {
			acceptor.bind(new InetSocketAddress(10001));
			System.out.println("监听端口:" + 10001);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
